package drivers

import (
	"context"

	"gitee.com/bitwormhole/mails-pnp-driver/lib/common/dto"
	"github.com/starter-go/mails"
)

////////////////////////////////////////////////////////////////////////////////
// driver

type myDriverForEmail struct {
	parent *Registry
}

func (inst *myDriverForEmail) _impl() mails.Driver {
	return inst
}

func (inst *myDriverForEmail) Accept(cfg *mails.Configuration) bool {
	return cfg.Driver == driverNameEmail
}

func (inst *myDriverForEmail) CreateDispatcher(cfg *mails.Configuration) (mails.Dispatcher, error) {
	disp := &myDispatcherForEmail{
		parent: inst.parent,
		config: cfg,
	}
	return disp, nil
}

////////////////////////////////////////////////////////////////////////////////
// Dispatcher

type myDispatcherForEmail struct {
	parent *Registry
	config *mails.Configuration
}

func (inst *myDispatcherForEmail) _impl() mails.Dispatcher {
	return inst
}

func (inst *myDispatcherForEmail) Accept(c context.Context, msg *mails.Message) bool {
	a1 := msg.FromAddress
	a2 := inst.config.SenderAddress
	return a1 == a2
}

func (inst *myDispatcherForEmail) Send(c context.Context, msg *mails.Message) error {
	obj, err := convertMessageToVO(msg, dto.TypeEmail)
	if err != nil {
		return err
	}
	ser := inst.parent.PNPService
	return ser.Push(c, obj)
}

////////////////////////////////////////////////////////////////////////////////
